import { BASE_URL } from '../utils/server.js';

export function request({ url, method = 'GET', data = {}, header = {} }) {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token');
		const authHeader = token ? { 'Authorization': `Bearer ${token}` } : {};
		uni.request({
			url: BASE_URL + url,
			method,
			data,
			header: { 'Content-Type': 'application/json', ...authHeader, ...header },
			success: (res) => {
				if (res.statusCode >= 200 && res.statusCode < 300) {
					resolve(res.data);
				} else {
					reject(res);
				}
			},
			fail: reject
		});
	});
}

export const api = {
	getCategories() {
		return request({ url: '/api/categories' });
	},
	getBanners() {
		return request({ url: '/api/banners' });
	},
	// cart (userId from JWT)
	cartList(){ return request({ url:'/api/cart/list' }); },
	cartAdd(payload){ return request({ url:'/api/cart/add', method:'POST', data: payload }); },
	cartUpdate(payload){ return request({ url:'/api/cart/update', method:'POST', data: payload }); },
	cartRemove(productId){ return request({ url:`/api/cart/remove?productId=${productId}`, method:'POST' }); },
	// orders (userId from JWT)
	checkout(){ return request({ url:'/api/orders/checkout', method:'POST' }); },
	checkoutSelected(payload){ return request({ url:'/api/orders/checkoutSelected', method:'POST', data: payload }); },
	getOrders(params){ return request({ url:'/api/orders', data: params||{} }); },
	getRefunds(){ return request({ url:'/api/refunds' }); },
	getRefundDetail(id){ return request({ url:`/api/refunds/${id}` }); },
	deleteRefund(id){ return request({ url:`/api/refunds/${id}`, method:'DELETE' }); },
	applyRefund(payload){ return request({ url:'/api/refunds', method:'POST', data: payload }); },
	// reviews
	getProductReviews(productId, params){ return request({ url:`/api/products/${productId}/reviews`, data: params||{} }); },
	createReview(payload){ return request({ url:'/api/reviews', method:'POST', data: payload }); },
	confirmOrder(orderId){ return request({ url:`/api/orders/${orderId}/confirm`, method:'POST' }); },
	payOrder(orderId){ return request({ url:`/api/orders/${orderId}/pay`, method:'POST' }); },
	getProducts(params) {
		return request({ url: '/api/products', data: params });
	},
	getProduct(id) {
		return request({ url: `/api/products/${id}` });
	},
	getUserProfile() {
		return request({ url: '/api/users/profile' });
	},
	// favorites
	getFavorites(){ return request({ url:'/api/favorites' }); },
	checkFavorite(productId){ return request({ url:`/api/favorites/check`, data:{ productId } }); },
	addFavorite(productId){ return request({ url:`/api/favorites/${productId}`, method:'POST' }); },
	removeFavorite(productId){ return request({ url:`/api/favorites/${productId}`, method:'DELETE' }); },
	// coupons
	getUserCoupons(){ return request({ url:'/api/users/coupons' }); },
	couponCheckin(){ return request({ url:'/api/coupons/checkin', method:'POST' }); },
	// addresses
	getAddresses(){ return request({ url:'/api/user/addresses' }); },
	createAddress(payload){ return request({ url:'/api/user/addresses', method:'POST', data: payload }); },
	updateAddress(payload){ return request({ url:`/api/user/addresses/${payload.id}`, method:'PUT', data: payload }); },
	setDefaultAddress(id){ return request({ url:`/api/user/addresses/${id}/default`, method:'POST' }); },
	updateUserProfile(payload) {
		return request({ url: '/api/users/profile', method: 'PUT', data: payload });
	},
	// posts
	getPosts(params) {
		return request({ url: '/api/posts', data: params || {} });
	},
	getPost(id) {
		return request({ url: `/api/posts/${id}` });
	},
	createPost(payload) {
		return request({ url: '/api/posts', method: 'POST', data: payload });
	},
	uploadPostImage(filePath) {
		return new Promise((resolve, reject) => {
			const token = uni.getStorageSync('token');
			const authHeader = token ? { 'Authorization': `Bearer ${token}` } : {};
			uni.uploadFile({
				url: BASE_URL + '/api/posts/upload',
				filePath: filePath,
				name: 'file',
				header: authHeader,
				success: (res) => {
					try {
						const data = JSON.parse(res.data);
						resolve(data);
					} catch (e) {
						reject(e);
					}
				},
				fail: reject
			});
		});
	},
	togglePostLike(postId) {
		return request({ url: `/api/posts/${postId}/like`, method: 'POST' });
	},
	togglePostFavorite(postId) {
		return request({ url: `/api/posts/${postId}/favorite`, method: 'POST' });
	},
	getPostComments(postId) {
		return request({ url: `/api/posts/${postId}/comments` });
	},
	createPostComment(postId, payload) {
		return request({ url: `/api/posts/${postId}/comments`, method: 'POST', data: payload });
	},
	toggleCommentLike(postId, commentId) {
		return request({ url: `/api/posts/${postId}/comments/${commentId}/like`, method: 'POST' });
	},
	getFavoritePosts() {
		return request({ url: '/api/posts/favorites' });
	},
	getAvailableCoupons(orderAmount) {
		const params = orderAmount ? { orderAmount } : {};
		return request({ url: '/api/coupons/available', data: params });
	},
	getRecommendations() {
		return request({ url: '/api/products/recommend' });
	},
	getMemberInfo() {
		return request({ url: '/api/member/info' });
	},
	joinMember() {
		return request({ url: '/api/member/join', method: 'POST' });
	},
	claimMemberCoupon(memberLevelCouponId) {
		return request({ url: `/api/member/coupon/claim?memberLevelCouponId=${memberLevelCouponId}`, method: 'POST' });
	},
	uploadAvatar(filePath) {
		return new Promise((resolve, reject) => {
			const token = uni.getStorageSync('token');
			const authHeader = token ? { 'Authorization': `Bearer ${token}` } : {};
			uni.uploadFile({
				url: BASE_URL + '/api/users/avatar/upload',
				filePath: filePath,
				name: 'file',
				header: authHeader,
				success: (res) => {
					try {
						const data = JSON.parse(res.data);
						resolve(data);
					} catch (e) {
						reject(e);
					}
				},
				fail: reject
			});
		});
	}
};


